package com.huaao.micropolice.root.security;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.huaao.micropolice.core.model.system.User;
import com.huaao.micropolice.core.security.CredentialsDigest;
import com.huaao.micropolice.core.security.CredentialsMatcherAdapter;
import com.huaao.micropolice.core.service.system.RoleService;
import com.huaao.micropolice.core.service.system.UserService;

public class UserRealm extends AuthorizingRealm implements InitializingBean{
	
	@Autowired
    private UserService userService;
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private CredentialsDigest credentialsDigest;
    
    @Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
		User u = (User) principals.getPrimaryPrincipal();
		User user = userService.findByUserid(u.getId());
		if (user != null) {
			auth.setStringPermissions(roleService.findPermissions(user));
		}
		return auth;
	}
    
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
    	UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		// token.getc
		User user = userService.findByUsername(token.getUsername());
		if (user != null) {
			byte[] salt = user.getSaltBytes();
			return new SimpleAuthenticationInfo(new User(user.getId(),user.getUsername()), user.getPassword(), ByteSource.Util.bytes(salt), getName());
		} else {
			return null;
		}
    }
    
    @Override
    public void afterPropertiesSet() throws Exception {
		CredentialsMatcher matcher = new CredentialsMatcherAdapter(credentialsDigest);
		setCredentialsMatcher(matcher);
	}
}
